package com.neudu.yiyang.service.impl;

import com.neudu.yiyang.mapper.BedMapper;
import com.neudu.yiyang.mapper.BeddetailsMapper;
import com.neudu.yiyang.mapper.CustomerMapper;
import com.neudu.yiyang.pojo.Bed;
import com.neudu.yiyang.pojo.Beddetails;
import com.neudu.yiyang.pojo.Customer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class BedTransferService {

    @Autowired
    private BedMapper bedMapper;

    @Autowired
    private BeddetailsMapper beddetailsMapper;

    @Autowired
    private CustomerMapper customerMapper;

    @Transactional
    public String transferBed(Integer beddetailId, Integer newBedId) {
        // 检查床位详情记录是否存在
        Beddetails beddetails = beddetailsMapper.selectById(beddetailId);
        if (beddetails == null) {
            return "未找到对应的床位详情记录";
        }

        // 检查新床位是否存在
        Bed newBed = bedMapper.selectById(newBedId);
        if (newBed == null) {
            return "新床位ID不存在";
        }

        // 检查新床位是否空闲
        if (newBed.getBedStatus() != 1) {
            return "新床位状态不为空闲，无法调换";
        }

        // 获取原床位信息
        Bed originalBed = bedMapper.selectById(beddetails.getBedId());
        if (originalBed != null) {
            // 将原床位状态设置为空闲
            bedMapper.updateStatus(originalBed.getId(), 1);
        }

        // 更新床位详情记录中的床位ID
        beddetailsMapper.updateBedId(beddetails.getId(), newBedId);

        // 更新新床位状态为有人
        bedMapper.updateStatus(newBed.getId(), 2);

        // 更新顾客表中的床位ID
        Customer customer = customerMapper.selectById(beddetails.getCustomerId());
        if (customer != null) {
            customerMapper.updateBedId(customer.getId(), newBedId);
        }

        return "床位调换成功";
    }
}